// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Xml.Linq;


namespace DailyBread
{
    /// <summary>
    /// Provides facade for accessing digg service
    /// </summary>
    public static class HttpService
    {
        /// <summary>
        /// Searches the specified search text.
        /// </summary>
        /// <param name="searchText">The search text.</param>
        /// <param name="onSearchCompleted">The on search completed.</param>
        /// <param name="onError">The on error.</param>
        public static void Get(Uri uri, Action<string> onGetCompleted = null, Action<string, Exception> onError = null, Action onFinally = null)
        {
            WebClient webClient = new WebClient();
            
            // register on download complete event
            webClient.DownloadStringCompleted += delegate (object sender, DownloadStringCompletedEventArgs e) 
            {
                try
                {
                    // report error
                    if (e.Error != null)
                    {
//#if DEBUG
//                        onSearchCompleted(GetStoriesMock());
//                        return;
//#endif
                        if (onError != null)
                        {
                            onError(uri.ToString(), e.Error);
                        }
                        return;
                    }

                    // notify completed callback
                    if (onGetCompleted != null)
                    {
                        onGetCompleted(e.Result);
                    }
                }
                finally
                {
                    // notify finally callback
                    if (onFinally != null)
                    {
                        onFinally();
                    }
                }
            };

            // start get
            webClient.DownloadStringAsync(uri);   
           
        }

    }
}